/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import service.Universe;
import service.UniverseFacadeREST;


/**
 *
 * @author andrew
 */
public class getUniverseList extends HttpServlet {

    @EJB
    private UniverseFacadeREST universeManager;
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String pathFileXML = request.getServletContext().getRealPath("/") + "Universes/"+"universeList.xml";
        
        writeXMLFile(pathFileXML, request, response);
        
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    
    
    private void writeXMLFile(String pathXML, HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        
        try {
            
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            
            // root (universes) elements
            Document doc = docBuilder.newDocument();
            Element universes = doc.createElement("universes");
            doc.appendChild(universes);
            
            //creo elemento universe
            List<Universe> universeList = universeManager.findAll();
                
            Iterator<Universe> universeIt = universeList.iterator();
            Universe tmpUniverse;
            while(universeIt.hasNext()){
                
                tmpUniverse = universeIt.next();
                
                // inserisco in XML solo gli universi validati
                if(tmpUniverse.getIsValidated()){
                    
                    // universeElement
                    Element universeElement = doc.createElement("universe");
                    universes.appendChild(universeElement);

                    // set attribute <id> to universe element
                        Attr attr_id_universe = doc.createAttribute("id");
                        attr_id_universe.setValue(tmpUniverse.getIdUniverse().toString());
                        universeElement.setAttributeNode(attr_id_universe);

                        // set attribute <name> to universe element
                        Attr attr_name_universe = doc.createAttribute("name");
                        attr_name_universe.setValue(tmpUniverse.getName());
                        universeElement.setAttributeNode(attr_name_universe);

                    // description in universe
                    Element descriprionUniverseElement = doc.createElement("description");
                    descriprionUniverseElement.appendChild(doc.createTextNode(tmpUniverse.getDescription()));
                    universeElement.appendChild(descriprionUniverseElement);

                    // UUID in universe
                    //generate random UUIDs
                    UUID uuid = UUID.randomUUID();

                    Element uuidElement = doc.createElement("UUID");
                    uuidElement.appendChild(doc.createTextNode(uuid.toString()));
                    universeElement.appendChild(uuidElement);

                    // number of planets
                    Element planetNumberElement = doc.createElement("numplanets");
                    planetNumberElement.appendChild( doc.createTextNode(String.valueOf(tmpUniverse.getPlanetCollection().size())) );
                    universeElement.appendChild(planetNumberElement);

                    // description in universe
                    String pathZip = request.getServletContext().getRealPath("/") + "Universes/"+tmpUniverse.getIdUniverse()+".zip";

                    Element universeSizeElement = doc.createElement("size");
                    universeSizeElement.appendChild(doc.createTextNode(String.valueOf(getFileSize(pathZip))));
                    universeElement.appendChild(universeSizeElement);
                    
                    String pathAvatar = "avatar/"+tmpUniverse.getIdUniverse()+".png";

                    Element avatarElement = doc.createElement("avatarpath");
                    avatarElement.appendChild(doc.createTextNode(pathAvatar));
                    universeElement.appendChild(avatarElement);

                }
            }
            
            // controllo se esiste già file XML e in caso affermativo, lo cancello
            File fileUniverseListXML = new File(pathXML);

            //verifica se la directory esiste
            if (!fileUniverseListXML.exists()) {
                System.out.println(" universeList XML file does not exist.");
            } else {

                try {
                    delete(fileUniverseListXML);
                } catch (Exception e) {
                }
            }
            
            
            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            DOMSource source = new DOMSource(doc);
            StreamResult resultInFile = new StreamResult(new File(pathXML));
            StreamResult resultInResponse = new StreamResult(response.getWriter());

            response.setCharacterEncoding("ISO-8859-1");
            out = response.getWriter();

            transformer.transform(source, resultInFile);
            transformer.transform(source, resultInResponse);

            System.out.println("File universeList generated!");
            
            
            
        } catch (IOException ex) {
            Logger.getLogger(getUniverseList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(getUniverseList.class.getName()).log(Level.SEVERE, null, ex);
        }catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } finally {
            out.close();
        } 
        
    }
    
    
    private int getFileSize(String path){
        
        File file =new File(path);

        if(file.exists()){

                double bytes = file.length();
                double kilobytes = (bytes / 1024);
                double megabytes = (kilobytes / 1024);

                return (int)megabytes;
        }else{
            System.out.println("File does not exists!");    
            return -1;    
        }
    }
    
    
    
    
    private static void delete(File file) throws IOException {

        if (file.isDirectory()) {

            //directory è vuota, quindi si può cancellare
            if (file.list().length == 0) {
                file.delete();
                System.out.println("Directory is deleted : " + file.getAbsolutePath());
            } else {

                //lista di tutte le sottodirectory contenute
                String files[] = file.list();

                for (String temp : files) {
                    //construttore file
                    File fileDelete = new File(file, temp);

                    //cancellazione ricorsiva
                    delete(fileDelete);
                }

                //controllo se directory è vuota e in caso affermativo la rimuovo
                if (file.list().length == 0) {
                    file.delete();
                    System.out.println("Directory is deleted : " + file.getAbsolutePath());
                }
            }

        } else {
            //se è file lo si cancella
            file.delete();
            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }
}
